<template>
  <Layout>
    <div class="organization-center">
      <!-- 面包屑导航 -->
      <div class="breadcrumb">
        当前位置：<router-link to="/home" class="breadcrumb-link">首页</router-link> > <span
          class="breadcrumb-current">组织中心</span>
      </div>

      <div class="content-wrapper">
        <!-- 左侧组织信息卡片 -->
        <div class="info-card">
          <div class="avatar-section">
            <img :src="organizationInfo.avatarUrl || '/default-avatar.png'" alt="组织头像" class="avatar">
            <el-upload class="avatar-uploader" action="http://localhost:9090/api/upload/image" :show-file-list="false"
              :on-success="handleAvatarSuccess">
              <el-button size="small">更换头像</el-button>
            </el-upload>
          </div>
          <div class="organization-info">
            <h3>{{ organizationInfo.organizationName }}</h3>
            <p><strong>组织编号：</strong>{{ organizationInfo.organizationId }}</p>
            <p><strong>成立时间：</strong>{{ formatDate(organizationInfo.establishmentDate) }}</p>
            <p><strong>人员规模：</strong>{{ organizationInfo.personnelScale }}</p>
            <p><strong>联系人：</strong>{{ organizationInfo.contactPerson }}</p>

            <!-- 培训满意度 -->
            <p><strong>培训满意度：</strong>
              <el-rate v-model="organizationInfo.trainingSatisfaction" disabled show-score></el-rate>
            </p>

            <!-- 合作满意度 -->
            <p><strong>合作满意度：</strong>
              <el-rate v-model="organizationInfo.cooperationSatisfaction" disabled show-score></el-rate>
            </p>

            <!-- 执行合规性 -->
            <p><strong>执行合规性：</strong>
              <el-rate v-model="organizationInfo.executionCompliance" disabled show-score></el-rate>
            </p>

            <!-- 星级评分 -->
            <p><strong>星级评分：</strong>
              <el-rate v-model="organizationInfo.starRating" disabled show-score></el-rate>
            </p>

            <p><strong>地址：</strong>{{ organizationInfo.address }}</p>
            <p><strong>详细地址：</strong>{{ organizationInfo.detailedAddress }}</p>
            <p><strong>组织简介：</strong>{{ organizationInfo.organizationProfile }}</p>
          </div>
        </div>

        <!-- 右侧主要内容区 -->
        <div class="main-content">
          <el-tabs v-model="activeTab">
            <!-- 志愿者列表 -->
            <el-tab-pane label="志愿者列表" name="volunteers">
              <el-table :data="volunteersList" style="width: 100%">
                <el-table-column prop="name" label="姓名"></el-table-column>
                <el-table-column prop="volunteerId" label="志愿者编号"></el-table-column>
                <el-table-column prop="totalServiceHours" label="累计服务时长"></el-table-column>
                <el-table-column prop="systemRank" label="系统等级"></el-table-column>
                <el-table-column label="评分" width="200">
                  <template #default="scope">
                    <el-rate v-model="scope.row.rating" show-score
                      @change="(val) => handleRatingChange(val, scope.row)"></el-rate>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>

            <!-- 活动列表 -->
            <el-tab-pane label="活动列表" name="activities">
              <el-table :data="activitiesList" style="width: 100%">
                <el-table-column prop="activityName" label="活动名称"></el-table-column>
                <el-table-column prop="startDate" label="开始时间">
                  <template #default="scope">
                    {{ formatDate(scope.row.startDate) }}
                  </template>
                </el-table-column>
                <el-table-column prop="endDate" label="结束时间">
                  <template #default="scope">
                    {{ formatDate(scope.row.endDate) }}
                  </template>
                </el-table-column>
                <el-table-column prop="activityStatus" label="状态">
                  <template #default="scope">
                    {{ getActivityStatus(scope.row.activityStatus) }}
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template #default="scope">
                    <el-button @click="navigateToEditActivity(scope.row)" type="primary" size="small"
                      :disabled="isActivityCompletedOrCancelled(scope.row.activityStatus)">编辑</el-button>
                    <el-button @click="deleteActivity(scope.row)" type="danger" size="small"
                      :disabled="isActivityCompletedOrCancelled(scope.row.activityStatus)">删除</el-button>
                    <el-button @click="openVolunteerDrawer(scope.row.activityId)"
                      type="primary" size="small">查看志愿者</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>

      <!-- 全局志愿者弹窗 -->
      <el-drawer v-model="drawerVisible" title="志愿者名单" direction="rtl" size="50%" :modal="true" :append-to-body="true" :with-header="true" :show-close="true" :close-on-click-modal="true" :close-on-press-escape="true" :destroy-on-close="false" :modal-class="'custom-drawer'" style="z-index: 9999;">
        <div class="drawer-content">
          <h2 class="drawer-title">活动志愿者名单</h2>
          <el-table :data="activityVolunteerList" style="width: 100%" :border="true" class="volunteer-table">
            <el-table-column prop="name" label="姓名" min-width="100">
              <template #default="scope">
                <div class="volunteer-name">{{ scope.row.name }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="phone" label="联系方式" min-width="120">
              <template #default="scope">
                <div class="volunteer-phone">{{ scope.row.phoneNumber }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="评分" min-width="100">
              <template #default="scope">
                <div class="volunteer-phone">{{ scope.row.systemRank }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="总服务时长" min-width="100">
              <template #default="scope">
                <div class="volunteer-phone">{{ scope.row.totalServiceHours }}</div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-drawer>
    </div>
  </Layout>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import Layout from '@/components/Layout.vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()
const activeTab = ref('volunteers')

// 组织信息
const organizationInfo = ref({
  avatarUrl: '',
  organizationName: '',
  organizationId: '',
  establishmentDate: '',
  personnelScale: 0,
  contactPerson: '',
  trainingSatisfaction: 0,
  cooperationSatisfaction: 0,
  executionCompliance: 0,
  starRating: 0,
  address: '',
  detailedAddress: '',
  organizationProfile: ''
})

// 志愿者列表
const volunteersList = ref([])

// 活动列表
const activitiesList = ref([])

const formatTime = (row, column, cellValue) => {
  return cellValue ? new Date(cellValue).toLocaleString() : "Invalid Date";
};

const formatDate = (date) => {
  return date ? new Date(date).toLocaleDateString() : "Invalid Date";
};

const getActivityStatus = (status) => {
  switch (status) {
    case "1":
      return '待开始';
    case "2":
      return '进行中';
    case "3":
      return '已结束';
    case "4":
      return '已取消';
    default:
      return '未知状态';
  }
};

const isActivityCompletedOrCancelled = (status) => {
  return status === 3 || status === 4;
};

// 获取组织信息
const fetchOrganizationInfo = async () => {
  try {
    // 从缓存获取organizationId
    const organizationId = localStorage.getItem('organid')
    console.log("organizationId=" + organizationId)
    if (!organizationId) {
      ElMessage.error('未找到组织ID')
      return
    }

    // 调用后端接口获取组织信息
    const response = await axios.get(`http://localhost:9090/organizations/${organizationId}`)
    if (response) {
      console.log(response)
      const organizationData = response.data
      console.log(organizationData)
      organizationInfo.value = {
        avatarUrl: organizationData.avatarUrl,
        organizationName: organizationData.organizationName,
        organizationId: organizationData.organizationId,
        establishmentDate: organizationData.establishmentDate,
        personnelScale: organizationData.personnelScale,
        contactPerson: organizationData.contactPerson,
        trainingSatisfaction: organizationData.trainingSatisfaction,
        cooperationSatisfaction: organizationData.cooperationSatisfaction,
        executionCompliance: organizationData.executionCompliance,
        starRating: organizationData.starRating,
        address: organizationData.address,
        detailedAddress: organizationData.detailedAddress,
        organizationProfile: organizationData.organizationProfile
      }

      // 获取志愿者列表
      const volunteersResponse = await axios.get(`http://localhost:9090/volunteers/searchByOrganizationId?organizationId=${organizationId}`)
      if (volunteersResponse.status === 200) {
        volunteersList.value = volunteersResponse.data || []
      }

      // 获取组织对所有志愿者的评分
      const ratingsResponse = await axios.get(`http://localhost:9090/volunteer-rating/by-organization/${organizationId}`);
      if (ratingsResponse.status === 200) {
        const ratingsData = ratingsResponse.data;

        // 确保返回的数据格式正确，并且 status 为 success
        if (ratingsData.status === 'success' && Array.isArray(ratingsData.data)) {
          // 创建一个评分映射表
          const ratingsMap = {};
          ratingsData.data.forEach(rating => {
            ratingsMap[rating.volunteerId] = rating.rating;
          });

          // 为每个志愿者设置评分
          volunteersList.value.forEach(volunteer => {
            volunteer.rating = ratingsMap[volunteer.volunteerId] || 0;
          });
        } else {
          console.log('Error: Invalid data format or unsuccessful response.');
        }
      } else {
        console.log('Error fetching ratings data.');
      }

      // 获取活动列表
      const activitiesResponse = await axios.get(`http://localhost:9090/activities/search?organizationId=${organizationId}`)
      if (activitiesResponse.status === 200) {
        activitiesList.value = activitiesResponse.data || []
      }

    } else {
      // ElMessage.error('获取组织信息失败')
    }
  } catch (error) {
    // ElMessage.error('获取组织信息失败')
  }
}

// 处理评分变化
const handleRatingChange = async (rating, volunteer) => {
  try {
    const organizationId = localStorage.getItem('organid')
    // 将响应数据转换为 JSON 格式并输出

    // 先查询是否存在评分记录
    const existingRatings = await axios.get(`http://localhost:9090/volunteer-rating/by-organization/${organizationId}/${volunteer.volunteerId}`)
    let response;
    if (existingRatings.data.data && existingRatings.data.data.length > 0) {
      // 如果存在评分记录且有评分,则更新
      response = await axios.put('http://localhost:9090/volunteer-rating/update', {
        id: existingRatings.data.data[0].id,
        volunteerId: volunteer.volunteerId,
        organizationId: organizationId,
        rating: rating
      })
    } else {
      // 如果不存在评分记录或评分为0,则新增
      response = await axios.post('http://localhost:9090/volunteer-rating/add', {
        volunteerId: volunteer.volunteerId,
        organizationId: organizationId,
        rating: rating
      })
    }
    if (response.status === 200) {
      ElMessage.success('评分更新成功')
      // 重新获取评分数据并更新页面
      const ratingsResponse = await axios.get(`http://localhost:9090/volunteer-rating/by-organization/${organizationId}`);
      if (ratingsResponse.status === 200 && ratingsResponse.data.status === 'success') {
        const ratingsMap = {};
        ratingsResponse.data.data.forEach(rating => {
          ratingsMap[rating.volunteerId] = rating.rating;
        });
        volunteersList.value.forEach(volunteer => {
          volunteer.rating = ratingsMap[volunteer.volunteerId] || 0;
        });
      }
    } else {
      ElMessage.error(existingRating && existingRating.rating ? '评分更新失败' : '评分添加失败')
    }

  } catch (error) {
    ElMessage.error('评分操作失败')
  }
}

// 头像上传成功处理
const handleAvatarSuccess = async (response) => {
  console.log(response)
  if (response) {
    try {
      const updateResponse = await axios.put(`http://localhost:9090/organizations/update`, {
        organizationId: organizationInfo.value.organizationId,
        avatarUrl: "http://localhost:9090/api/upload/uploads/" + response
      })

      if (updateResponse.status === 200) {
        ElMessage.success('头像更新成功')
        await fetchOrganizationInfo() // 重新加载组织信息
      } else {
        ElMessage.error('头像更新失败')
      }
    } catch (error) {
      ElMessage.error('头像更新失败')
    }
  } else {
    ElMessage.error('头像上传失败')
  }
}

const navigateToEditActivity = (activity) => {
  router.push({ name: 'EditActivity', params: { activityId: activity.activityId } }).catch(err => {
    if (err.name !== 'NavigationDuplicated') {
      throw err;
    }
  });
}

const deleteActivity = async (activity) => {
  try {
    const response = await axios.delete(`http://localhost:9090/activities/${activity.activityId}`)
    if (response.status === 200) {
      ElMessage.success('活动删除成功')
      await fetchOrganizationInfo() // 重新加载组织信息
    } else {
      ElMessage.error('活动删除失败')
    }
  } catch (error) {
    ElMessage.error('活动删除失败')
  }
}


const drawerVisible = ref(false)
const activityVolunteerList = ref([])

const openVolunteerDrawer = async (activityId) => {
  drawerVisible.value = true;
  await fetchActivityVolunteers(activityId);
}

const fetchActivityVolunteers = async (activityId) => {
  try {
    const response = await axios.get(`http://localhost:9090/volunteers/searchByActivate?activate=${activityId}`)
    if (response.status === 200) {
      activityVolunteerList.value = response.data || []
    }
  } catch (error) {
    ElMessage.error('获取志愿者列表失败')
  }
}

onMounted(() => {
  fetchOrganizationInfo()
})
</script>

<style scoped>
.organization-center {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
}

.breadcrumb-link {
  color: #dd2b2b;
  text-decoration: none;
}

.breadcrumb-link:hover {
  color: #66b1ff;
}

.breadcrumb-current {
  color: #dd2b2b;
}

.content-wrapper {
  display: flex;
  gap: 20px;
}

.info-card {
  width: 300px;
  background: #fff;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  text-align: center;
  transition: all 0.3s ease;
}

.info-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
}

.avatar-section {
  text-align: center;
  margin-bottom: 24px;
}

.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  margin-bottom: 16px;
  border: 4px solid #dd2b2b;
  transition: all 0.3s ease;
  object-fit: cover;
}

.avatar:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(221, 43, 43, 0.2);
}

.organization-info {
  text-align: left;
}

.organization-info h3 {
  margin-bottom: 16px;
  color: #dd2b2b;
  font-size: 1.5rem;
  font-weight: 600;
}

.organization-info p {
  margin: 8px 0;
  color: #666;
  font-size: 14px;
  line-height: 1.6;
  display: flex;
  align-items: center;
  gap: 8px;
}

.organization-info p strong {
  color: #333;
  min-width: 80px;
}

.main-content {
  flex: 1;
  background: #fff;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
  background-color: #ebeef5;
}

:deep(.el-tabs__item) {
  color: #666;
  font-size: 15px;
  padding: 0 24px;
  height: 40px;
  line-height: 40px;
  transition: all 0.3s ease;
}

:deep(.el-tabs__item.is-active) {
  color: #dd2b2b;
  font-weight: 600;
}

:deep(.el-tabs__active-bar) {
  background-color: #dd2b2b;
  height: 3px;
  border-radius: 3px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #333;
  font-weight: 600;
  padding: 12px 0;
}

:deep(.el-table td) {
  padding: 16px 0;
}

:deep(.el-button) {
  transition: all 0.3s ease;
}

:deep(.el-button:hover) {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.custom-drawer :deep(.el-drawer) {
  background-color: rgba(255, 255, 255, 0.95) !important;
  backdrop-filter: blur(8px);
  border: 1px solid rgba(221, 43, 43, 0.1);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1) !important;
  z-index: 2001 !important;
}

.custom-drawer :deep(.el-drawer__header) {
  margin-bottom: 0;
  padding: 20px;
  background: rgba(255, 255, 255, 0.9);
  border-bottom: 1px solid rgba(221, 43, 43, 0.1);
  position: relative;
  z-index: 2002;
}

.custom-drawer :deep(.el-overlay) {
  z-index: 2000 !important;
  background-color: rgba(0, 0, 0, 0.3);
  backdrop-filter: blur(5px);
}

.drawer-content {
  padding: 20px;
}

.drawer-title {
  font-size: 18px;
  color: #333;
  margin-bottom: 20px;
  font-weight: 600;
}

.volunteer-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.volunteer-name {
  font-weight: 500;
  color: #333;
}

.volunteer-phone {
  color: #666;
}

.status-tag {
  border-radius: 4px;
  padding: 6px 12px;
}

:deep(.el-table) {
  --el-table-border-color: #ebeef5;
  --el-table-header-bg-color: #f5f7fa;
}

:deep(.el-table th) {
  font-weight: 600;
  color: #333;
  background-color: var(--el-table-header-bg-color);
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table--border) {
  border-radius: 8px;
}

:deep(.el-drawer__body) {
  padding: 0;
}

:deep(.el-drawer__container) .el-overlay {
  background-color: rgba(245, 245, 245, 0.7);
  backdrop-filter: blur(3px);
  transition: all 0.3s ease;
}

:deep(.el-drawer.rtl) {
  box-shadow: -2px 0 12px rgba(0, 0, 0, 0.1);
  border-left: 1px solid #e4e7ed;
  transition: transform 0.3s cubic-bezier(0.23, 1, 0.32, 1);
}
</style>